package com.franklin.ideaplugin.api.utils.psi;

import cn.hutool.core.collection.CollectionUtil;
import com.intellij.psi.PsiElement;
import com.intellij.psi.util.PsiTreeUtil;
import org.jetbrains.annotations.Nullable;

import java.util.Collection;

/**
 * @author Ye Junhui
 * @since 2024/3/22
 */
public class PsiTreeUtils {

    /**
     * 寻找最后一个子节点
     *
     * @param psiElement
     * @param childType
     * @param <T>
     * @return
     */
    @Nullable
    public static <T extends PsiElement> T findLastChild(PsiElement psiElement, Class<T> childType) {
        Collection<T> children = PsiTreeUtil.findChildrenOfType(psiElement, childType);
        if (CollectionUtil.isEmpty(children)) {
            return null;
        }
        Object[] array = children.toArray();
        return (T) array[array.length - 1];
    }

    /**
     * 寻找最后一个节点
     *
     * @param psiElement
     * @param childType
     * @param <T>
     * @return
     */
    @Nullable
    public static <T extends PsiElement> T findLastElement(PsiElement psiElement, Class<T> childType) {
        Collection<T> children = PsiTreeUtil.collectElementsOfType(psiElement, childType);
        if (CollectionUtil.isEmpty(children)) {
            return null;
        }
        Object[] array = children.toArray();
        return (T) array[array.length - 1];
    }
}
